import AV from 'leancloud-storage'
AV.init({
  appId: 'M575N2lR1Ct7Xbq74eCj1KUU-gzGzoHsz',
  appKey: 'PJT19CONwhK0cbjA0jS6Gb0R'
})
window.AV = AV
const { User, Role, Cloud, Query, Object: avObject } = window.AV
const roleQuery = new Query(Role)
export default {
  requestSmsCode: Cloud.requestSmsCode,
  login: User.logIn,
  usersByMobilePhone: User.usersByMobilePhone,
  getInfo: User.current,
  getInfoAsync: User.currentAsync,
  logout: User.logOut,
  exportData (className) {
    const classQuery = new Query(className)
    return classQuery.find()
  },
  query (className, parameter) {
    const classQuery = new Query(className)
    classQuery.limit(parameter.pageSize)
    classQuery.skip(parameter.pageSize * (parameter.pageNo - 1))
    return classQuery.find()
  },
  add (className, obj) {
    const SaveData = avObject.extend(className)
    const saveData = new SaveData(obj)
    return saveData.save()
  },
  delete (className, id) {
    const classDelete = avObject.createWithoutData(className, id)
    classDelete.destroy()
    return classDelete.save()
  },
  updateSignUp (id, qualifications) {
    const signUp = avObject.createWithoutData('signUp', id)
    signUp.set('qualifications', qualifications)
    return signUp.save()
  },
  queryCount (className) {
    return new Query(className).count()
  },
  update (className, obj, id) {
    const signUp = avObject.createWithoutData(className, id)
    signUp.set(obj)
    return signUp.save()
  },
  destroyAll (className, ids) {
    const objects = []
    ids.map(id => {
      objects.push(avObject.createWithoutData(className, id))
    })
    return avObject.destroyAll(objects)
  },
  addAdmin () {

  },
  queryAdmin () {
    // 查询 name 等于 Administrator 的角色
    roleQuery.equalTo('name', 'admin')
    return new Promise((resolve, reject) => {
      roleQuery.first().then((adminRole) => {
        const userRelation = adminRole.relation('users')
        return userRelation.query().find()
      }).then((userList) => {
        resolve(userList)
      }).catch((error) => {
        reject(error)
      })
    })
    // roleQuery.find().then((adminRole) => {
    //   console.log(adminRole)
    //   const userRelation = adminRole.relation('users')
    //   return userRelation.query().find()
    // }).then((userList) => {
    //   return userList
    // }).catch((error) => {
    //   console.log(error)
    // })
  }
}
